//
//  LSUserInfoInputViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/20.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSUserInfoInputViewController.h"

@interface LSUserInfoInputViewController () <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *inputTextField;
@property (nonatomic, strong) UIButton *doneButton;
@end

@implementation LSUserInfoInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = [NSString stringWithFormat:@"设置%@",self.titleText];
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithCustomView:self.doneButton];
    self.navigationItem.rightBarButtonItem = doneItem;
    self.doneButton.enabled = false;
    [self.view addSubview:self.inputTextField];
    self.inputTextField.text = self.currentText;
    [self.inputTextField becomeFirstResponder];
    if ([self.titleText rangeOfString:@"姓名"].length > 0) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.inputTextField];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([newText isEqualToString:self.currentText]) {
        self.doneButton.enabled = false;
    } else {
        self.doneButton.enabled = true;
    }
    if ([self.title rangeOfString:@"手机"].length > 0) {
        if (![ValidateUtils validateMobile:newText]) {
            self.doneButton.enabled = false;
        } else {
            self.doneButton.enabled = true;
        }
        if (newText.length < 11) {
            self.doneButton.enabled = false;
        } else {
            self.doneButton.enabled = true;
        }
    } else {
        if (newText.length < 2) {
            self.doneButton.enabled = false;
        } else {
            self.doneButton.enabled = true;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if ([self.titleText rangeOfString:@"姓名"].length > 0) {
        //过滤非汉字字符
        textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
        if (textField.text.length >= 10) {
            textField.text = [textField.text substringToIndex:10];
        }
        return NO;
    } else {
        return YES;
    }
}

- (void)textFiledEditChanged:(id)notification{
    UITextRange *selectedRange = self.inputTextField.markedTextRange;
    UITextPosition *position = [self.inputTextField positionFromPosition:selectedRange.start offset:0];
    if (!position) { // 没有高亮选择的字
        //过滤非汉字字符
        self.inputTextField.text = [self filterCharactor:self.inputTextField.text withRegex:@"[^\u4e00-\u9fa5]"];
        if (self.inputTextField.text.length >= 10) {
            self.inputTextField.text = [self.inputTextField.text substringToIndex:10];
        }
    }else { //有高亮文字
        //do nothing
    }
}

//根据正则，过滤特殊字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}

- (UITextField *)inputTextField {
    if (!_inputTextField) {
        _inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 15, ScreenWidth, 44)];
        _inputTextField.backgroundColor = UIColor.whiteColor;
        _inputTextField.layer.borderColor = hexColor(999999).CGColor;
        _inputTextField.layer.borderWidth = 0.5;
        _inputTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 1)];
        _inputTextField.leftViewMode = UITextFieldViewModeAlways;
        _inputTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _inputTextField.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:16];
        _inputTextField.delegate = self;
        if ([self.title rangeOfString:@"手机"].length > 0) {
            _inputTextField.keyboardType = UIKeyboardTypePhonePad;
        }
    }
    return _inputTextField;
}

- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 44)];
        _doneButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:14];
        [_doneButton setTitle:@"确认" forState:UIControlStateNormal];
        [_doneButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_doneButton setTitleColor:UIColor.lightTextColor forState:UIControlStateDisabled];
        [_doneButton addTarget:self action:@selector(updateInfo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneButton;
}

- (void)updateInfo {
    NSDictionary *param = @{};
    if ([self.title rangeOfString:@"手机"].length > 0) {
        if ([self.inputTextField.text isEqualToString:@""]) {
            [MBProgressHUD showTipMessageInWindow:@"内容不可为空"];
            return;
        }
        if (![ValidateUtils validateMobile:self.inputTextField.text]) {
            [MBProgressHUD showTipMessageInWindow:@"手机号输入有误"];
            return;
        }
        param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"id":[ValidateUtils validateNull:[UserInfoModel sharedInstance].customerId],@"mobilephone":self.inputTextField.text,@"sex":[UserInfoModel sharedInstance].customerSex,@"realname":[UserInfoModel sharedInstance].customerRealName,@"post":[UserInfoModel sharedInstance].customerCategoryId};
    } else {
        if ([self.inputTextField.text isEqualToString:@""]) {
            [MBProgressHUD showTipMessageInWindow:@"内容不可为空"];
            return;
        }
        if (self.inputTextField.text.length < 2) {
            [MBProgressHUD showTipMessageInWindow:@"姓名长度过短"];
            return;
        }
        if (self.inputTextField.text.length > 10) {
            [MBProgressHUD showTipMessageInWindow:@"姓名长度过长"];
            return;
        }
        param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"id":[ValidateUtils validateNull:[UserInfoModel sharedInstance].customerId],@"mobilephone":[UserInfoModel sharedInstance].customerMobile,@"sex":[UserInfoModel sharedInstance].customerSex,@"realname":self.inputTextField.text,@"post":[UserInfoModel sharedInstance].customerCategoryId};
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:UserUpdate param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        NSNumber *status = [responseObject objectForKey:@"status"];
        if (status.integerValue == 200) {
            [MBProgressHUD showTipMessageInWindow:@"修改成功"];
            if ([self.title rangeOfString:@"手机"].length > 0) {
                [UserInfoModel sharedInstance].customerMobile = self.inputTextField.text;
            } else {
                [UserInfoModel sharedInstance].customerRealName = self.inputTextField.text;
            }
            WS
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:true];
            });
        } else {
            [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:responseObject[@"message"]]];
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
